<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>牛马饲料剂量器</title>
    <style>

            .workday-checkbox {
                margin: 0 0.5rem 0 1rem;
            }
            .input-group label:not(:first-child) {
                display: inline-block;
                margin-right: 1rem;
            }
            .password-toggle {
                background: none;
                border: none;
                color: #d4af37;
                cursor: pointer;
                margin-left: 0.5rem;
            }
            .hidden {
                -webkit-text-security: disc;
                text-security: disc;
            }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                max-width: 800px;
                margin: 0 auto;
                padding: 30px;
                background-color: #1a1a1a;
                color: #f8f8f8;
            }
            .container {
                background-color: #252525;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            }
            .input-group {
                margin-bottom: 1.5rem;
            }
            label {
                display: block;
                margin-bottom: 0.8rem;
                font-weight: 600;
                color: #d4af37;
            }
            input[type="number"] {
                width: 60%;
                padding: 0.8rem;
                border: 2px solid #333;
                border-radius: 5px;
                background-color: #333;
                color: #f8f8f8;
                transition: border-color 0.3s;
            }
            .input-group {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
            }
            .input-group label {
                width: 100%;
            }
            .input-group input[type="number"] {
                flex: 1;
                min-width: 0;
            }
            .input-group button:not(.password-toggle) {
                margin-left: 0.5rem;
            }
            .input-group.faded label:not(:first-child) {
                display: inline-block;
                margin-right: 1rem;
            }
            .input-group.faded {
                flex-wrap: wrap;
            }
            .input-group.faded label {
                width: 100%;
                display: block;
            }
            .input-group.faded label:not(:first-child) {
                display: block;
                width: 100%;
                margin-right: 0;
            }
            input[type="number"]:focus {
                outline: none;
                border-color: #d4af37;
            }
            button {
                background-color: #d4af37;
                color: #1a1a1a;
                border: none;
                padding: 0.8rem 1.5rem;
                border-radius: 5px;
                cursor: pointer;
                font-weight: 600;
                transition: background-color 0.3s;
            }
            button:hover {
                background-color: #b89a2e;
            }
            .progress-container {
                width: 80%; /* 可根据需要调整宽度 */
                background-color: #333;
                border-radius: 5px;
                margin: 1.5rem auto;
                position: relative;
                height: 25px;
            }
            .progress-bar {
                height: 100%;
                background-color: #d4af37;
                border-radius: 5px;
                width: 0%;
                transition: width 0.3s;
            }
            #progress-percentage {
                position: absolute;
                top: 100%;
                left: 50%;
                transform: translateX(-50%);
                margin-top: 8px;
                color: #d4af37;
                font-weight: 600;
            }
            #current-date {
                margin: 1rem 0;
                font-size: 1rem;
                color: #f8f8f8;
                text-align: center;
            }
            .toggle-collapse {
                background-color: #d4af37;
                color: #1a1a1a;
                border: none;
                padding: 0.8rem 1.5rem;
                border-radius: 5px;
                cursor: pointer;
                font-weight: 600;
                transition: background-color 0.3s;
                margin-bottom: 1rem;
            }
            .collapsible-content {
                display: none;
            }
            .big-amount {
                font-size: 3rem;
                font-weight: bold;
                color: #d4af37;
                margin: 2rem 0;
                text-align: center;
            }
            .input-group.faded {
                opacity: 0.7;
                transition: opacity 0.3s;
            }
            .input-group.faded:hover {
                opacity: 1;
            }
            
            .progress-bar {
                position: relative;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            #progress-percentage {
                color: #1a1a1a;
                font-weight: bold;
                position: absolute;
                left: 50%;
                top: calc(50% + 12.5px);
                transform: translate(-50%, -50%);
                pointer-events: none;
            }
            #purchase-prompt {
                text-align: center;
                margin: 1rem 0;
                color: #d4af37;
                font-size: 1.2rem;
            }
        </style>
</head>
<body>
        <div class="container">
            <div id="earned-amount" class="big-amount">本月你已经赚到了 0.00 元！</div>
            <div class="progress-container">
                <div class="progress-bar" id="progress-bar">
                    <span id="progress-percentage"></span>
            </div>
        </div>
        <div id="current-date"></div>
        <div id="purchase-prompt"></div>

            <button class="toggle-collapse">设置</button>
            <div class="collapsible-content">
                <label>
                    <input type="checkbox" id="compact-mode" checked> 精简版
                </label>
            <div class="input-group faded">
                <label for="monthly-salary">设置月薪 (元):</label>
                <div style="display: flex; align-items: center; width: 100%;">
                    <input type="number" id="monthly-salary" placeholder="输入月薪">
                    <button class="password-toggle" onclick="toggleSalaryVisibility()">👁️</button>
                    <button onclick="setSalary()">设置月薪</button>
                </div>
            </div>
            <div class="input-group faded">
                <label>选择工作日期:</label>
                <label><input type="checkbox" class="workday-checkbox" value="0"> 周日</label>
                <label><input type="checkbox" class="workday-checkbox" value="1"> 周一</label>
                <label><input type="checkbox" class="workday-checkbox" value="2"> 周二</label>
                <label><input type="checkbox" class="workday-checkbox" value="3"> 周三</label>
                <label><input type="checkbox" class="workday-checkbox" value="4"> 周四</label>
                <label><input type="checkbox" class="workday-checkbox" value="5"> 周五</label>
                <label><input type="checkbox" class="workday-checkbox" value="6"> 周六</label>
            </div>
            <div class="input-group faded">
                <label>设置每日工作时间:</label>
                <label>开始时间: <input type="time" id="work-start" value="09:00"></label>
                <label>午休开始: <input type="time" id="lunch-start" value="12:00"></label>
                <label>午休结束: <input type="time" id="lunch-end" value="13:00"></label>
                <label>结束时间: <input type="time" id="work-end" value="18:00"></label>
            </div>
        </div>
        <div id="error-message" class="error"></div>
    </div>
    <div id="current-date"></div>
    </div>

    <script>
        let monthlySalary = parseFloat(localStorage.getItem('monthlySalary')) || 0;
let selectedWorkdays = JSON.parse(localStorage.getItem('selectedWorkdays')) || [];
let workStart = localStorage.getItem('workStart') || '09:00';
let lunchStart = localStorage.getItem('lunchStart') || '12:00';
let lunchEnd = localStorage.getItem('lunchEnd') || '13:00';
let workEnd = localStorage.getItem('workEnd') || '18:00';

function saveWorkHours() {
    workStart = document.getElementById('work-start').value;
    lunchStart = document.getElementById('lunch-start').value;
    lunchEnd = document.getElementById('lunch-end').value;
    workEnd = document.getElementById('work-end').value;
    localStorage.setItem('workStart', workStart);
    localStorage.setItem('lunchStart', lunchStart);
    localStorage.setItem('lunchEnd', lunchEnd);
    localStorage.setItem('workEnd', workEnd);
}

        function getCurrentMonthSeconds() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const lastDay = new Date(year, month + 1, 0).getDate();
            // 计算当月总秒数
            return lastDay * 24 * 60 * 60;
        }

        function getElapsedSeconds() {
            const now = new Date();
            const firstOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
            return Math.floor((now - firstOfMonth) / 1000);
        }

        function updateDate() {
            const now = new Date();
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            const timeString = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
            document.getElementById('current-date').textContent = `${now.toLocaleDateString('zh-CN', options)} ${timeString}`;
        }

        function toggleCollapse() {
            const content = document.querySelector('.collapsible-content');
            if (content.style.display === 'block') {
                content.style.display = 'none';
            } else {
                content.style.display = 'block';
            }
        }

        // 为折叠按钮添加事件监听
        document.querySelector('.toggle-collapse').addEventListener('click', toggleCollapse);

        function getDailyWorkSeconds() {
    const workStartParts = workStart.split(':');
    const lunchStartParts = lunchStart.split(':');
    const lunchEndParts = lunchEnd.split(':');
    const workEndParts = workEnd.split(':');
    
    const workStartDate = new Date();
    workStartDate.setHours(workStartParts[0], workStartParts[1], 0);
    const lunchStartDate = new Date();
    lunchStartDate.setHours(lunchStartParts[0], lunchStartParts[1], 0);
    const lunchEndDate = new Date();
    lunchEndDate.setHours(lunchEndParts[0], lunchEndParts[1], 0);
    const workEndDate = new Date();
    workEndDate.setHours(workEndParts[0], workEndParts[1], 0);
    
    return ((lunchStartDate - workStartDate) + (workEndDate - lunchEndDate)) / 1000;
}

function updateSalary() {
            let earned = 0;
            let progress = 0;
            if (monthlySalary > 0) {
                const now = new Date();
                const currentYear = now.getFullYear();
                const currentMonth = now.getMonth();
                const monthStart = new Date(currentYear, currentMonth, 1);
                const monthEnd = new Date(currentYear, currentMonth + 1, 0);
                const monthDays = monthEnd.getDate();
                
                // 收集当月所有选中的日期
                  const selectedDates = [];
                  for (let day = 1; day <= monthDays; day++) {
                      const date = new Date(currentYear, currentMonth, day);
                      if (selectedWorkdays.includes(date.getDay())) {
                          selectedDates.push(date);
                      }
                  }
                  
                  // 如果没有选择日期，已赚金额为 0
                  if (selectedDates.length === 0) {
                      earned = 0;
                      progress = 0;
                  } else {
                      const currentDate = new Date(now);
                      currentDate.setHours(0, 0, 0, 0);
                      
                      // 计算已过去的选中日期数量
                      let completedDays = 0;
                      for (const date of selectedDates) {
                          if (date < currentDate) {
                              completedDays++;
                          }
                      }
                      
                      // 检查当前日期是否是选中日期
                      const isTodaySelected = selectedDates.some(date => 
                          date.toDateString() === currentDate.toDateString()
                      );
                      
                      // 计算当天已过去的工作秒数
                      let todayWorkSeconds = 0;
                      if (isTodaySelected) {
                          const nowHours = now.getHours();
                          const nowMinutes = now.getMinutes();
                          const nowSeconds = now.getSeconds();
                          const nowTime = new Date();
                          nowTime.setHours(nowHours, nowMinutes, nowSeconds);
                          
                          const workStartParts = workStart.split(':');
                          const lunchStartParts = lunchStart.split(':');
                          const lunchEndParts = lunchEnd.split(':');
                          const workEndParts = workEnd.split(':');
                          
                          const workStartDate = new Date(currentDate);
                          workStartDate.setHours(workStartParts[0], workStartParts[1], 0);
                          const lunchStartDate = new Date(currentDate);
                          lunchStartDate.setHours(lunchStartParts[0], lunchStartParts[1], 0);
                          const lunchEndDate = new Date(currentDate);
                          lunchEndDate.setHours(lunchEndParts[0], lunchEndParts[1], 0);
                          const workEndDate = new Date(currentDate);
                          workEndDate.setHours(workEndParts[0], workEndParts[1], 0);
                          
                          if (nowTime >= workStartDate && nowTime < lunchStartDate) {
                              todayWorkSeconds = (nowTime - workStartDate) / 1000;
                          } else if (nowTime >= lunchEndDate && nowTime < workEndDate) {
                              todayWorkSeconds = ((lunchStartDate - workStartDate) + (nowTime - lunchEndDate)) / 1000;
                          } else if (nowTime >= workEndDate) {
                              todayWorkSeconds = getDailyWorkSeconds();
                          }
                      }
                      
                      // 每天的金额 = 总金额 / 选中天数
                      const dailyAmount = monthlySalary / selectedDates.length;
                      // 每秒金额 = 每天金额 / 每天工作秒数
                      const perSecondAmount = dailyAmount / getDailyWorkSeconds();
                      
                      // 已赚金额 = 已完成天数的金额 + 当天已赚金额
                      earned = completedDays * dailyAmount + todayWorkSeconds * perSecondAmount;
                      
                      earned = Math.min(earned, monthlySalary);
                      progress = (earned / monthlySalary) * 100;
                  }
                document.getElementById('earned-amount').textContent = `本月你已经赚到了 ${earned.toFixed(2)} 元！`;
                  document.getElementById('progress-bar').style.width = `${progress.toFixed(2)}%`;
                  document.getElementById('progress-percentage').textContent = `${progress.toFixed(2)}%`;
                  
                  let purchaseItem = '';
                  if (earned < 0.1) {
                      purchaseItem = '棒棒糖';
                  } else if (earned < 1) {
                      purchaseItem = '打火机';
                  } else if (earned < 5) {
                      purchaseItem = '雪糕';
                  } else if (earned < 10) {
                      purchaseItem = '泡面';
                  } else if (earned < 20) {
                      purchaseItem = '奶茶';
                  } else if (earned < 50) {
                      purchaseItem = '电影票';
                  } else if (earned < 100) {
                      purchaseItem = '西餐套餐';
                  } else if (earned < 200) {
                      purchaseItem = 'T恤';
                  } else if (earned < 500) {
                      purchaseItem = '运动鞋';
                  } else if (earned < 1000) {
                      purchaseItem = '机械键盘';
                  } else if (earned < 2000) {
                      purchaseItem = '平板电脑';
                  } else if (earned < 5000) {
                      purchaseItem = '智能手表';
                  } else if (earned < 10000) {
                      purchaseItem = 'iPhone';
                  } else if (earned < 20000) {
                      purchaseItem = '轻薄笔记本电脑';
                  } else if (earned < 50000) {
                      purchaseItem = '专业相机';
                  } else {
                      purchaseItem = '入门级镜头';
                  }
                  
                  document.getElementById('purchase-prompt').textContent = `本月赚到的钱已经够买一个 ${purchaseItem}！`;
            }
            setTimeout(updateSalary, 1000);
        }

        function setSalary() {
            const input = document.getElementById('monthly-salary').value;
            const errorElement = document.getElementById('error-message');
            try {
                const newSalary = parseFloat(input);
                if (isNaN(newSalary) || newSalary < 0) {
                    throw new Error('请输入有效的正数金额');
                }
                monthlySalary = newSalary;
                localStorage.setItem('monthlySalary', newSalary);
                errorElement.textContent = '';
            } catch (error) {
                errorElement.textContent = error.message;
            }
        }

        function toggleSalaryVisibility() {
            const salaryInput = document.getElementById('monthly-salary');
            salaryInput.classList.toggle('hidden');
        }

        function updateSelectedWorkdays() {
            const checkboxes = document.querySelectorAll('.workday-checkbox');
            selectedWorkdays = Array.from(checkboxes)
                .filter(checkbox => checkbox.checked)
                .map(checkbox => parseInt(checkbox.value));
            localStorage.setItem('selectedWorkdays', JSON.stringify(selectedWorkdays));
        }

        // 初始化复选框状态
        function initWorkdayCheckboxes() {
            const checkboxes = document.querySelectorAll('.workday-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectedWorkdays.includes(parseInt(checkbox.value));
                checkbox.addEventListener('change', updateSelectedWorkdays);
            });
        }

        // 页面加载时初始化
        window.onload = function() {
            initWorkdayCheckboxes();
        }

        // 初始化工作时间输入框
        document.getElementById('work-start').value = workStart;
        document.getElementById('lunch-start').value = lunchStart;
        document.getElementById('lunch-end').value = lunchEnd;
        document.getElementById('work-end').value = workEnd;
        
        // 添加工作时间输入框的事件监听
        document.getElementById('work-start').addEventListener('change', saveWorkHours);
        document.getElementById('lunch-start').addEventListener('change', saveWorkHours);
        document.getElementById('lunch-end').addEventListener('change', saveWorkHours);
        document.getElementById('work-end').addEventListener('change', saveWorkHours);
        
        // 初始化
        document.getElementById('monthly-salary').value = monthlySalary;
        updateDate();
    </script>
    <script>
        let isCompactMode = document.getElementById('compact-mode').checked;
        updateDisplay();
        updateSalary();
        setInterval(updateDate, 1000);
        saveWorkHours();
        
        function updateDisplay() {
            const earnedAmount = document.getElementById('earned-amount');
            const purchasePrompt = document.getElementById('purchase-prompt');
            if (isCompactMode) {
                earnedAmount.textContent = earnedAmount.textContent.match(/\d+\.\d{2}/)[0];
                const match = purchasePrompt.textContent.match(/本月赚到的钱已经够买一个(.*)！/);
                purchasePrompt.textContent = match ? match[1] : '';
            } else {
                fetch('/api/earned')
                   .then(response => response.text())
                   .then(text => {
                        earnedAmount.textContent = `本月你已经赚到了 ${text} 元！`;
                    });
                fetch('/api/purchase')
                   .then(response => response.text())
                   .then(text => {
                        purchasePrompt.textContent = `本月赚到的钱已经够买一个${text}！`;
                    });
            }
        }
        
        document.getElementById('compact-mode').addEventListener('change', function() {
            isCompactMode = this.checked;
            updateDisplay();
        });
        
        // 在数据更新后调用显示更新
        const originalUpdateSalary = updateSalary;
        updateSalary = function() {
            originalUpdateSalary();
            updateDisplay();
        };
    </script>
</body>
</html>